//
//  SeachViewController.m
//  CWeekly
//
//  Created by  on 12-5-13.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SeachViewController.h"
@interface SeachViewController ()

@end

@implementation SeachViewController
-(void)dealloc{
    [searchArray release];
    [bookArray release];
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        searchArray=[[NSMutableArray alloc] init];
        bookArray=[[NSMutableArray alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    UISearchBar* bar=[[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    bar.delegate = self;
    bar.barStyle=UIBarStyleBlack;
    bar.translucent=YES;
    bar.placeholder=@"请输入杂志名称";
    [self.view addSubview:bar];
    [bar release];
   [bookArray addObjectsFromArray:[[NSUserDefaults standardUserDefaults] arrayForKey:@"BOOKS"]];
    
    
    resultTab=[[UITableView alloc] initWithFrame:CGRectMake(0, 44, 320, 500-44) style:UITableViewStylePlain];
    resultTab.delegate=self;
    resultTab.dataSource=self;
    [self.view addSubview:resultTab];
    [resultTab release];
}
#pragma mark UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
	[searchBar resignFirstResponder];
	[searchBar setShowsCancelButton:NO animated:YES];
    //获取搜索结果
    [searchArray removeAllObjects];
    for (int i=0; i<bookArray.count; i++) {
        NSDictionary* book=[bookArray objectAtIndex:i];
        NSString* bookname=[book valueForKey:@"mgTitle"];
//        NSString* desc=[book valueForKey:@"mgDescribe"];
        if ([bookname rangeOfString:searchBar.text].location!=NSNotFound) {
            [searchArray addObject:book];
        }
    }
    [resultTab reloadData];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText   // called when text changes (including clear)
{
    [searchArray removeAllObjects];
    [resultTab reloadData];

}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
	[searchBar setShowsCancelButton:YES animated:YES];
	UIButton *cancelBt = (UIButton *)[searchBar.subviews objectAtIndex:2];
	[cancelBt setTitle:@"取消" forState:UIControlStateNormal];
	cancelBt.frame = CGRectMake(cancelBt.frame.origin.x, 
								cancelBt.frame.origin.y, 
								100, 
								cancelBt.frame.size.height);
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
	[searchBar resignFirstResponder];
	[searchBar setShowsCancelButton:NO animated:YES];
}

#pragma mark table
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 114;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return searchArray.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString* identy=@"cell";
    UITableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:identy];
    if (cell==nil) {
        cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identy] autorelease];
    }
    NSDictionary*d=[searchArray objectAtIndex:indexPath.row];
    cell.textLabel.text=[d valueForKey:@"mgTitle"];
    cell.detailTextLabel.text=[self isbookExist:d];

    NSString *strUrl = [NSString stringWithFormat:IMAGE_URL,[d objectForKey:@"mgImg"]];
    
    ImageDownloader *imageDownloader = [[ImageDownloader alloc]initWithUrl:strUrl index:indexPath.row];
    imageDownloader.delegate = self;
    UIImage *image = [imageDownloader getImage];
    if (nil == image) {
        image = [UIImage imageNamed:@"smallloading_v.png"];//默认图片
    }
    [imageDownloader release];
    cell.imageView.image=image;
    return cell;
}

-(NSString*)isbookExist:(NSDictionary*)book{
    NSString* mgId=[ NSString stringWithFormat:@"%@",[book valueForKey:@"mgId"]];
    NSString *rootPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/BookData"];
    NSString *bookPath = [rootPath stringByAppendingPathComponent:mgId];
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/TempData"];
    NSString *tempPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.temp",mgId]];
    if ([[NSFileManager defaultManager] fileExistsAtPath:bookPath]) {
        return @"已下载";
    }
    if([[NSFileManager defaultManager] fileExistsAtPath:tempPath]){
        return @"正在下载";
    }
        return @"未下载";

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary* book=[searchArray objectAtIndex:indexPath.row];
    NSUInteger p=[bookArray indexOfObject:book];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"searchSelect" object:[NSNumber numberWithInt:p]];

}

- (void)imageDidFinishLoad:(UIImage *)image index:(NSInteger)index
{
	if (image) {
        UITableViewCell* cell=[resultTab cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
		cell.imageView.image = image;
	}
}
#pragma mark -
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
